#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from sys import exit

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
from PyQt4.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel

srcFileName = "commemorative_eu.db"
dstFileName = "commemorative_eu.mobile.db"
imageField = "obverseimg"
imageHeight = 80
imageFullHeight = 480

app = QtGui.QApplication(sys.argv)

srcDb = QSqlDatabase.addDatabase('QSQLITE', "source")
srcDb.setDatabaseName(srcFileName)
if not srcDb.open():
    print("Can't open %s" % srcFileName)
    exit(1)

model = QSqlTableModel(db=srcDb)
model.setTable('coins')
model.setFilter("status='owned' OR status='demo'")
model.select()
print(model.rowCount())

dstDb = QSqlDatabase.addDatabase('QSQLITE', "destination")
dstDb.setDatabaseName(dstFileName)
if not dstDb.open():
    print("Can't open %s" % dstFileName)
    exit(1)
sql = """CREATE TABLE coins (
        id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
        title CHAR,
        value NUMERIC(10,2),
        unit CHAR,
        country CHAR,
        year NUMERIC(4),
        period CHAR,
        mint CHAR,
        mintmark CHAR(10),
        issuedate CHAR,
        type CHAR,
        series CHAR,
        subjectshort CHAR,
        status CHAR,
        grade CHAR,
        mintage INTEGER,
        subject TEXT,
        image BLOB,
        obverseimg BLOB,
        reverseimg BLOB,
        features TEXT,
        createdat CHAR,
        updatedat CHAR
    )"""
QSqlQuery(sql, dstDb)

sql = """CREATE TABLE settings (
        title CHAR NOT NULL UNIQUE,
        value CHAR
    )"""
QSqlQuery(sql, dstDb)
sql = """INSERT INTO settings (title, value) VALUES ('Version', 'M1')"""
QSqlQuery(sql, dstDb)

dstModel = QSqlTableModel(db=dstDb)
dstModel.setTable('coins')
dstModel.select()
if dstModel.rowCount() > 0:
    print("Not empty file %s" % dstFileName)
    exit(1)

for i in range(model.rowCount()):
    record = model.record(i)
    newRecord = dstModel.record()
    print(record.value("status"))
    for name in ['title', 'value', 'unit', 'country', 'year', 'period', 'mint',
                 'mintmark', 'issuedate', 'type', 'series', 'subjectshort',
                 'status', 'grade', 'mintage', 'subject', 'image', 'obverseimg',
                 'reverseimg', 'features', 'createdat', 'updatedat']:
        value = None
        if name == 'image':
            value = record.value(imageField)
            if not record.isNull(imageField):
                image = QtGui.QImage()
                image.loadFromData(value)
                ba = QtCore.QByteArray() 
                buffer = QtCore.QBuffer(ba)
                buffer.open(QtCore.QIODevice.WriteOnly)
                scaledImage = image.scaled(imageHeight, imageHeight,
                                           Qt.KeepAspectRatio, Qt.SmoothTransformation)
                scaledImage.save(buffer, 'png')
                value = ba
        elif name in ['obverseimg', 'reverseimg']:
            value = record.value(name)
            if not record.isNull(name):
                image = QtGui.QImage()
                image.loadFromData(value)
                if image.width() > imageFullHeight or image.height() > imageFullHeight:
                    ba = QtCore.QByteArray()
                    buffer = QtCore.QBuffer(ba)
                    buffer.open(QtCore.QIODevice.WriteOnly)
                    scaledImage = image.scaled(imageFullHeight, imageFullHeight,
                                               Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    scaledImage.save(buffer, 'jpg')
                    value = ba
        else:
            value = record.value(name)

        newRecord.setValue(name, value)
    dstModel.insertRecord(-1, newRecord)

print("Done")
